<template>
  <!-- 搜索区和新增按钮 -->
  <el-row :gutter="20" class="mt-4">
    <el-col :span="8">
      <el-input 
        v-model="searchKey" 
        placeholder="搜索菜单名称" 
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" icon="Search" @click="handleSearch" />
        </template>
      </el-input>
    </el-col>
    <el-col :span="2">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增菜单
      </el-button>
    </el-col>
  </el-row>

  <!-- 菜单表格 -->
  <el-table 
    :data="menuList" 
    border 
    stripe 
    style="width: 100%; margin-top: 20px"
    row-key="id"
    :tree-props="{ hasChildren: 'children', children: 'children' }"
    :default-expand-all="true"
  >
    <el-table-column prop="name" label="菜单名称" width="180"></el-table-column>
    <el-table-column prop="icon" label="图标" width="100">
      <template #default="scope">
        <el-icon>
          <component :is="scope.row.icon" />
        </el-icon>
      </template>
    </el-table-column>
    <el-table-column prop="path" label="路径" />
     <el-table-column label="父级菜单" width="150">
      <template #default="scope">
        <!-- 根据 parentId 查找对应的菜单名称 -->
        <span>{{ getParentMenuName(scope.row.parentId) }}</span>
      </template>
    </el-table-column>
    <!-- 状态列 -->
    <el-table-column label="状态" width="150" align="center">
      <template #default="scope">
        <div v-if="scope.row.isActive === true" class="status-button enabled">
          启用
        </div>
        <div v-else class="status-button disabled">
          禁用
        </div>
      </template>
    </el-table-column>
    <!-- 操作 -->
    <el-table-column label="操作" width="250" align="center">
      <template #default="scope">
        <!-- 只有子菜单才能操作 -->
        <template v-if="!hasChildren(scope.row)">
          <el-button 
            size="small" 
            type="primary" 
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
           <el-button 
            size="small" 
            type="success" 
            v-if="!scope.row.isActive"
            @click="handleEnable(scope.row)"
          >
            启用
          </el-button>
          <el-button 
            size="small" 
            type="warning" 
            v-if="scope.row.isActive"
            @click="handleDisable(scope.row)"
          >
            禁用
          </el-button>
        </template>
        <template v-else>
          <span style="color: #999; font-size: 12px;">父级菜单不可操作</span>
        </template>
      </template>
    </el-table-column>
  </el-table>
    
  <!-- 菜单表单弹窗 -->
  <MenuForm 
    v-model="showFormDialog"
    :menu="formMenu"
    :menuList="menuList"
    @save="handleFormSave"
    @updateVisible="handleFormClose"
  />
</template>

<script setup>
import { ref, onMounted, reactive,watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import MenuForm from '../../components/business/MenuForm.vue'
import Pagination from '@/components/common/Pagination.vue'
import { menuApi } from '@/api/menu.js'; // 引入角色管理 API
import { useMenuStore } from '../../stores/menu'

const menuStore = useMenuStore()

// 搜索和分页状态
const searchKey = ref('')

const menuList = ref([])
const showFormDialog = ref(false)
const formMenu = ref(null)

// 页面初始化加载数据
onMounted(async () => {
  await loadMenus()
})

// 加载菜单数据
const loadMenus = async () => {
  try {
    const res = await menuApi.getMenuTree()      
    menuList.value = res    
  } catch (error) {
    console.error('加载菜单数据失败', error)
    ElMessage.error('加载菜单数据失败')
  }
}

// 递归搜索菜单树，避免重复
const recursiveSearch = (menus, keyword) => {
  return menus.reduce((result, menu) => {
    // 如果当前菜单匹配，直接添加整个菜单（包含所有子菜单）
    if (menu.name.toLowerCase().includes(keyword.toLowerCase())) {
      result.push({ ...menu });
      return result;
    }
    
    // 如果当前菜单不匹配，递归检查子菜单
    if (menu.children && menu.children.length > 0) {
      const childrenResult = recursiveSearch(menu.children, keyword);
      if (childrenResult.length > 0) {
        // 创建一个副本，只包含匹配的子菜单
        result.push({ 
          ...menu, 
          children: childrenResult 
        });
      }
    }
    return result;
  }, []);
};

// 搜索菜单
const handleSearch = () => {
  // 如果搜索关键词为空，显示所有菜单
  if (!searchKey.value) {
    loadMenus()
    return;
  }
  // 递归搜索菜单名称，模糊搜索菜单名称
  const filteredList = recursiveSearch(menuList.value, searchKey.value);
  // 更新菜单列表为搜索结果
  menuList.value = filteredList;

  console.log('搜索菜单:', searchKey.value);
};

// 新增菜单
const handleAdd = () => {
  formMenu.value = null
  showFormDialog.value = true
  
}

// 编辑菜单
const handleEdit = (row) => {
  formMenu.value = { ...row }
  showFormDialog.value = true
}

// 删除菜单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单"${row.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await menuApi.deleteMenu(row.id)
    await menuStore.refreshMenuTree()
    await loadMenus()
    ElMessage.success('菜单删除成功')
  } catch (error) {
    // 用户取消删除
    console.log('取消删除', error)
    ElMessage.error('删除菜单失败')
  }
}

// 保存表单（新增/编辑）
const handleFormSave = async (menuData) => {
  try{
    if (menuData.id) {
      // 编辑操作
      await menuApi.updateMenu(menuData.id, menuData)
      ElMessage.success('菜单编辑成功')
    } else {
      console.log(menuData);
      
      // 处理路径：如果是子菜单且路径不以/开头，则自动添加/
      let path = menuData.path
      if (menuData.parentId && path && !path.startsWith('/')) {
        path = '/' + path
      }
      
      const menuDataForCreate = {
        name: menuData.name,
        path: path,
        icon: menuData.icon || "Setting", // 默认图标
        parentId: menuData.parentId || null, // 显式设置为 null
        isActive: menuData.isActive ?? true, // 默认启用
      };
      
      // 新增操作
      let res = await menuApi.createMenu(menuDataForCreate) 

      ElMessage.success('菜单创建成功')
    }
    await menuStore.refreshMenuTree()
    await loadMenus() // 刷新菜单列表
  }catch(err){
    ElMessage.error('操作失败')
  }finally{
    showFormDialog.value = false // 关闭弹窗
  }
}

// 关闭新增/编辑弹窗
const handleFormClose = (visible) => {
  showFormDialog.value = visible
}

// 根据 parentId 获取父级菜单名称
// const getParentMenuName = (parentId) => {
//   if (!parentId) {
//     return '无';
//   }
//   const findMenu = (menus) => {
//     for (const menu of menus) {
//       if (menu.id === parentId) {
//         return menu.name;
//       }
//       if (menu.children) {
//         const result = findMenu(menu.children);
//         if (result) {
//           return result;
//         }
//       }
//     }
//     return null;
//   };
//   return findMenu(menuList.value) || '未知';
// };
const getParentMenuName = (parentId) => {
  if (!parentId) return '无'
  const parentMenu = menuStore.getMenuById(parentId)
  return parentMenu ? parentMenu.name : '未知'
}

// 检查菜单是否有子菜单
const hasChildren = (menu) => {
  return menu.children && menu.children.length > 0
}

// 启用菜单
const handleEnable = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要启用菜单"${row.name}"吗？`,
      '启用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await menuApi.enableMenu(row.id)
    await menuStore.refreshMenuTree() // 刷新全局菜单状态
    await loadMenus()
    ElMessage.success('菜单启用成功')
  } catch (error) {
    // 用户取消启用
    console.log('取消启用', error)
    ElMessage.error('启用菜单失败')
  }
}

// 禁用菜单
const handleDisable = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要禁用菜单"${row.name}"吗？`,
      '禁用确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await menuApi.disableMenu(row.id)
    await menuStore.refreshMenuTree()
    await loadMenus()
    ElMessage.success('菜单禁用成功')
  } catch (error) {
    // 用户取消禁用
    console.log('取消禁用', error)
    ElMessage.error('禁用菜单失败')
  }
}
</script>

<style scoped>
.pagination{
  justify-content: center;
  margin-top: 20px;
}

/* 表格操作列按钮间距 */
:deep(.el-table__column:last-child .el-button) {
  margin-right: 5px;
}

/* 状态按钮样式 */
.status-button {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 5px;
  font-weight: bold;
  text-align: center;
  cursor: pointer;
}

.enabled {
  background-color: #d0f5a579;
  color: #469f2e;
  border: 1px solid #d0f5a5;
}

.disabled {
  background-color: #ffe6e68c;
  color: #e44444;
  border: 1px solid #f9d2d2;
}
</style>